package cn.javass.dp.composite.example6;


import java.util.ArrayList;
import java.util.List;

/**
 * 组合对象
 */
public class Composite extends Compoment {

    @Override
    public void addChild(Compoment child) {
        //延时初始化
        if (childCompoments == null) {
            childCompoments = new ArrayList<>();
        }
        childCompoments.add(child);
        //设置树上下级关系
        child.setParent(this);

        //树节点路径不重复
        //设置根节点
        if (this.getCompomentPath() == null || this.getCompomentPath().trim().length() == 0) {
            this.setCompomentPath(this.name);
        }

        if (this.getCompomentPath().startsWith(child.getName()+".")) {
            throw  new IllegalArgumentException(child.getName()+"已经被添加过了");
        } else {
            if (this.getCompomentPath().indexOf(child.getName()) < 0) {
                String compomentPath = this.getCompomentPath() + "." +child.getName();
                child.setCompomentPath(compomentPath);
                System.out.println("compomentPath = " + compomentPath);
            } else {
                throw new IllegalArgumentException("组件" + child.getName() + "已经被添加过了");
            }
        }

    }

    @Override
    public String getName() {
        return name;
    }

    //移除某个商品
    @Override
    public void removeChild(Compoment child) {
        if (childCompoments != null) {
            int idx = childCompoments.indexOf(child);
            if (idx != -1) {
                for (Compoment c : child.getChildren()) {
                    c.setParent(this);
                    childCompoments.add(c);
                }
                childCompoments.remove(idx);
            }
        }
    }

    @Override
    public List<Compoment> getChildren() {
        return childCompoments;
    }


    /**
     * 用来存储组合对象中包含的子组件对象
     */
    private List<Compoment> childCompoments = null;

    private String name = "";

    public Composite(String name) {
        this.name = name;
    }


    @Override
    public void printStruct(String preName) {
        System.out.println(preName + "+" +this.name);
        //用于区分 composite 或者 leaf
        if (this.childCompoments != null) {
            preName +=  " ";
            for (Compoment childCompoment : childCompoments) {
                childCompoment.printStruct(preName);
            }
        }
    }


    @Override
    public Compoment getChildren(int index) {
        if (childCompoments != null) {
            if (index > 0 && index < childCompoments.size()) {
                return childCompoments.get(index);
            }
        }
        return null;
    }
}
